<template>
  <wd-form ref="form" :model="model" errorType="toast">
    <wd-cell-group border>
      <wd-input
        v-model="model.name"
        label="用户名"
        label-width="100px"
        prop="name"
        placeholder="请输入用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <wd-input
        v-if="!isEdit"
        v-model="model.password"
        label="密码"
        label-width="100px"
        prop="password"
        show-password
        placeholder="请输入密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <wd-input
        v-model="model.email"
        label="邮箱"
        label-width="100px"
        prop="email"
        placeholder="请输入邮箱"
        :rules="[{ required: true, message: '请填写邮箱' }]"
      />
      <wd-input
        v-model="model.phone"
        label="手机号"
        label-width="100px"
        prop="phone"
        placeholder="请输入手机号"
      />
      <wd-cell title="头像" title-width="100px">
        <wd-upload
          v-model:file-list="fileList"
          prop="avatar"
          image-mode="aspectFill"
          :action="action"
          :limit="1"
          @change="handleChange"
        />
      </wd-cell>
    </wd-cell-group>
    <div class="flex items-center justify-left mb-4 mt-2 pl-4">
      <wd-checkbox v-model="isAgree">阅读并同意</wd-checkbox>
      <div class="text-14px color-blue" @click="openContract">
        {{ privacyContractName }}
      </div>
    </div>
    <view class="footer px-4">
      <wd-button type="primary" size="large" block @click="handleSubmit">
        提交
      </wd-button>
    </view>
  </wd-form>
  <PrivacyPopup />
  <wd-toast />
</template>

<script setup lang="ts">
import { register, updateUserInfo } from '@/api/user';
import { useToast } from 'wot-design-uni';
import type { TRegisterReq } from '@/api/user/type';
import { UploadFile } from 'wot-design-uni/components/wd-upload/types';
import { ResultCodeEnum } from '@/enums';
import { useUserStore } from '@/store';
import { usePrivacy } from '@/composables/privacy';

const { isAgree, privacyContractName, openContract } = usePrivacy();

const userStore = useUserStore();
const isEdit = ref(false);
onLoad((options) => {
  console.log('打印***options', options);
  isEdit.value = options?.type === 'edit';
  if (isEdit.value) {
    uni.setNavigationBarTitle({
      title: '编辑资料'
    });
    model.name = userStore.userInfo.name;
    model.email = userStore.userInfo.email;
    model.phone = userStore.userInfo.phone;
    model.avatar = userStore.userInfo.avatar;
    fileList.value = [{ url: userStore.userInfo.avatar }];
  }
});

const fileList = ref<UploadFile[]>([]);
const model = reactive<TRegisterReq>({
  name: '',
  password: '',
  email: '',
  phone: '',
  avatar: ''
});

const action = import.meta.env.VITE_APP_UPLOAD_URL;

const handleChange = ({ fileList }: any) => {
  if (fileList.length) {
    model.avatar = JSON.parse(fileList[0].response).data.url;
  }
};

const form = ref();
const { success: showSuccess, info } = useToast();

const handleSubmit = async () => {
  const { valid } = await form.value.validate();
  console.log('打印***valid', valid);
  if (!valid) return;
  if (!isAgree.value) return info({ msg: '请阅读并同意隐私保护指引' });
  if (isEdit.value) {
    await updateInfo();
  } else {
    await registerInfo();
  }
};

const registerInfo = async () => {
  const res = await register(model);
  if (res.code === ResultCodeEnum.SUCCESS) {
    showSuccess({
      msg: '注册成功'
    });
    setTimeout(() => {
      uni.navigateTo({
        url: '/pages/center/login/index'
      });
    }, 1000);
  }
};

const updateInfo = async () => {
  const res = await updateUserInfo({
    name: model.name,
    email: model.email,
    phone: model.phone,
    avatar: model.avatar,
    id: userStore.userInfo.id
  });
  if (res.code === ResultCodeEnum.SUCCESS) {
    showSuccess({
      msg: '更新成功'
    });
    userStore.setUserInfo({
      ...res.data,
      accessToken: userStore.userInfo.accessToken,
      refreshToken: userStore.userInfo.refreshToken
    });
    setTimeout(() => {
      uni.switchTab({
        url: '/pages/center/index'
      });
    }, 1000);
  }
};
</script>

<style lang="scss" scoped></style>
